package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.subject.SubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.Map;

/**
 * 自定义 excel 读取接口实现类
 * @author He Wentao
 * @since 2022/8/21 21:40
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    // 采用手动构造器传入 service 对象
    public EduSubjectService subjectService;

    public SubjectExcelListener(EduSubjectService eduSubjectService){
        this.subjectService=eduSubjectService;
    }

    public SubjectExcelListener(){}

    // 一行一行读取 excel 内容，但是不包含表头
    @Override
    public void invoke(SubjectData data, AnalysisContext analysisContext) {

        if (data == null) {
            throw new RuntimeException("文件数据为空");
        }

        // 获取一级分类，查询是否存在
        EduSubject eduSubject = this.EduSubjectSelect(subjectService, data.getOneSubjectName());
        if (eduSubject==null){
            // 不存在就存入数据库
            eduSubject = new EduSubject();
            eduSubject.setTitle(data.getOneSubjectName());
            eduSubject.setParentId("0");
            subjectService.save(eduSubject);
        }

        // 判断二级分类是否存在，由于是一行数据，所以他前面的就是他的父分类
        // 前面的 一级 分类，无轮是查到了，还是没查到，最终都会有一个 id 值
        EduSubject eduSubject1 = this.EduSubjectSelect(subjectService, data.getTwoSubjectName(), eduSubject.getId());
        if (eduSubject1==null){
            eduSubject1 = new EduSubject();
            eduSubject1.setParentId(eduSubject.getId());
            eduSubject1.setTitle(data.getTwoSubjectName());
            subjectService.save(eduSubject1);

        }

    }


    // 读取完成之后执行
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    // 读取 excel 表头信息
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        System.out.println("表头信息:"+headMap);
    }

    // 查询一级分类是否存在
    private EduSubject EduSubjectSelect(EduSubjectService service,String title){
        return this.EduSubjectSelect(service,title,"0");
    }

    /**
     * 根据名称、父 id ，进行查询 二级分类 是否存在
     * @param service  service
     * @param title    标题
     * @param pid       父 id
     * @return          subject 对象，失败为 null
     */
    private EduSubject EduSubjectSelect(EduSubjectService service,String title,String pid) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",title);
        wrapper.eq("parent_id",pid);
        return service.getOne(wrapper);
    }
}
